package com.gopay.scheduler.job;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.batch.BatchPayStep;
import com.gopay.common.constants.batch.BatchProcessStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.DrawOpType;
import com.gopay.common.constants.trans.PayBankOpType;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.autosettle.AsBankLimitConfigDAO;
import com.gopay.common.cps.dao.bank.BisBankInfoMainDAO;
import com.gopay.common.cps.service.autosettle.impl.AutoSettleHelper;
import com.gopay.common.domain.autosettle.AsBankLimitConfig;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.gp.GP01301VO;
import com.gopay.common.domain.cps.transfer.BatchTransferToBankVO;
import com.gopay.common.domain.cps.transfer.Tran00700VO;
import com.gopay.common.domain.cps.transfer.Tran00800VO;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.CallCPSHelper;

/**
 * 自动结算统计银行已用额度
 * 
 * @AutoSettleStatiBankUsedQuota.java
 * @author fanghw
 * @2015年3月24日 上午10:25:57 www.gopay.com.cn Inc.All rights reserved.
 */
public class AutoSettleStatiBankUsedQuotaJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name = "asBankLimitConfigDAO")
    private AsBankLimitConfigDAO asBankLimitConfigDAO;
    
    @Resource(name = "bisBankInfoMainDAO")
    private BisBankInfoMainDAO bisBankInfoMainDAO;
    
    @Resource(name = "autoSettleHelper")
    private AutoSettleHelper autoSettleHelper;
    
    @Resource(name = "callCPSHelper")
    private CallCPSHelper callCPSHelper;

    @Override
    public void doJobInternal() {
        logger.error("AutoSettleStatiBankUsedQuota------start------");

        // 当前时间
        Date curDate = new Date();
        
        //工作日T+0银行已用额度Map
        Map<String,BigDecimal> bankMap=new HashMap<String,BigDecimal>();
        
        // 判断今天是否为工作日
        if (!autoSettleHelper.isHoliday(curDate)){
            //统计今天T+0银行已用额度
            bankMap=queryBankUsedQuota(curDate);
        }
        logger.error("--bankMap.size=" + bankMap.size());
        
        //获取所有银行配置列表
        List<AsBankLimitConfig> bankList = asBankLimitConfigDAO.findAll(AsBankLimitConfig.class);
        logger.error("--bankList.size=" + bankList.size());
        
        // 更新银行已用额度
        BigDecimal userQuota;
        for (AsBankLimitConfig bank : bankList) {
            userQuota=bankMap.get(bank.getBankCode());
            if(userQuota==null){
                userQuota=new BigDecimal(0);
            }
            logger.error("--bankCode=" + bank.getBankCode() + ",userQuota=" + userQuota);
            
            try {
                //更新到数据库
                updateBankUsedQuota(bank.getBankCode(),userQuota);

                logger.error("--update success");
            } catch (Exception e) {
                logger.error("--更新自动结算银行额度失败,bankCode=" + bank.getBankCode(), e);
            }
            
        }
        
       
        logger.error("AutoSettleStatiBankUsedQuota------end------");
    }
    
    private void updateBankUsedQuota(String bankCode,BigDecimal usedQuota){
        StringBuilder sb=new StringBuilder("update as_bank_limit_config t ");
        sb.append(" set t.today_settle_money=:usedQuota where t.bank_code=:bankCode ");
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("usedQuota",usedQuota);
        map.put("bankCode",bankCode);
        
        int value=asBankLimitConfigDAO.updateBySql(sb.toString(), map);
        logger.error("更新自动结算银行额度结果 bankCode="+bankCode+",usedQuota="+usedQuota+",value="+value);
    }

    /**
     * 查询银行已用额度
     * 
     * @param curDate
     * @return
     */
    private Map<String,BigDecimal> queryBankUsedQuota(Date curDate) {
        StringBuilder sb = new StringBuilder();        
        
        sb.append("   select m.out_stlm_id, sum(m.mer_txn_amt) ");
        sb.append("  from CPS_GEN_MAIN_ORDER m ");
        sb.append("   left join CPS_GEN_PAY_ORDER p on p.gopay_order_id = m.gopay_order_id ");
        sb.append("  where 1 = 1 ");
        sb.append("    and p.settlement_cycle = 0 ");
        sb.append("    and p.auto_settle = '1' ");
        sb.append("    and m.txn_sta_cd in (20000, 30102) ");
        sb.append("   and m.gopay_int_txn_cd in ('00700', '00800', '01301') ");//加上跨境人民币出口的 add by qld,之后有可能要改,目前先不做，删除20160905
        sb.append("   and m.order_stlm_time >= to_timestamp(:today, 'yyyymmddHH24miss') ");
        sb.append("  group by m.out_stlm_id ");

       
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("today", DateUtils.format(curDate, "yyyyMMdd") + "000000");

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);

        Map<String,BigDecimal> bankMap=new HashMap<String,BigDecimal>();
        if (rsList != null && rsList.size() > 0) {
            for (Object[] arr : rsList) {
                bankMap.put((String) arr[0], (BigDecimal) arr[1]);
            }
        }

        return bankMap;
    }
    
    

    
}
